package com.chaoxin.lovehelp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxin.lovehelp.aop.UnauthorizedException;
import com.chaoxin.lovehelp.common.enums.ErrorCode;
import com.chaoxin.lovehelp.common.exception.BusinessException;
import com.chaoxin.lovehelp.common.utils.MyMD5Util;
import com.chaoxin.lovehelp.service.RecipientService;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.enums.vo.allFellowVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoxin.lovehelp.common.utils.PageUtils;
import com.chaoxin.lovehelp.dao.FellowDao;
import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.service.FellowService;

import javax.servlet.http.HttpServletRequest;


@Service("fellowService")
public class FellowServiceImpl extends ServiceImpl<FellowDao, FellowEntity> implements FellowService {

    @Autowired
    private RecipientService recipientService;

    @Override
    public PageUtils queryPage(HttpServletRequest request, Map<String, Object> params) {
        //登录用户
        FellowEntity loginUser = (FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        //筛选条件
        String name = (String) params.get("name");//名字
        String type = (String) params.get("type");//类型
        String gender = (String) params.get("gender");//性别
        String origin = (String) params.get("origin");//住址

        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display",1);
        if(!StringUtils.isEmpty(name)){
            System.out.println(name);
            wrapper.like("name",name);

        }
        if(!StringUtils.isEmpty(type)){
            System.out.println(type);
            wrapper.eq("category",type);
        }
        if(!StringUtils.isEmpty(gender)){
            System.out.println(gender);
            wrapper.eq("gender",gender);
        }
        if(!StringUtils.isEmpty(origin)){
            System.out.println(origin);
            wrapper.like("address",origin);
        }
        //超级管理员和管理员能查询所有会员信息，普通用户只能查询自己信息
        if (loginUser.getRole()!=1 && loginUser.getRole()!=2){
            wrapper.eq("id",loginUser.getId());
        }
        //普通管理员只能看到普通用户
        if (loginUser.getRole()==2){
            wrapper.eq("role",3);
        }

        List<FellowEntity> fellows = this.list(wrapper);
        List<allFellowVo> vos = new ArrayList<>();
        for (FellowEntity item:fellows) {
            allFellowVo vo = new allFellowVo();
            BeanUtils.copyProperties(item,vo);
            vo.setRecipientNum(recipientService.getHelpNum(item.getId()));
            vos.add(vo);
        }
        if (loginUser.getRole()==2){
            //添加自己，并放到最前面
            allFellowVo vo = new allFellowVo();
            BeanUtils.copyProperties(loginUser,vo);
            vos.add(0,vo);
        }
        System.out.println("参数"+params);
        //分页处理
        Integer pageIndex = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        int from = (pageIndex - 1) * limit;
        int to = from + limit > vos.size() ? vos.size() : from + limit;
        List<allFellowVo> vos1 = new ArrayList<>(vos.subList(from, to));
        IPage<allFellowVo> page = new Page<>(pageIndex, limit);
        page.setRecords(vos1);
        page.setTotal(vos.size());
        page.setPages(vos.size() % limit > 0 ? vos.size() / limit + 1 : vos.size() / limit);
        return new PageUtils(page);

    }

    @Override
    public void removeIds(List<Integer> list) {
        if(list!=null){
            for (Integer id: list) {
                FellowEntity fellow= this.baseMapper.selectById(id);
                fellow.setIsDisplay(0);
                this.baseMapper.updateById(fellow);

            }
        }

    }

    //获取所有会员信息
    @Override
    public List<allFellowVo> getAllFellow() {
        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display",  1);
        List<FellowEntity> list = this.list(wrapper);

        // 初始化集合 + 防御空值
        List<allFellowVo> listVo = new ArrayList<>();
        if (list != null) {
            for (FellowEntity fellow : list) {
                listVo.add(this.transferAllFellowVo(fellow));
            }
        }
        return listVo;
    }

    @Override
    public Boolean authenticate(String tel, String password, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("tel",tel);
        wrapper.eq("is_display",1);
        FellowEntity loginFellowEntity = this.baseMapper.selectOne(wrapper);
        System.out.println(loginFellowEntity);
        if (loginFellowEntity == null) {
            return false;
        }
        System.out.println("登录密码加密后"+MyMD5Util.encrypt(password));
        if (MyMD5Util.verify(password, loginFellowEntity.getPassword())) {
            request.getSession().setAttribute(SystemEnum.LOGIN_STATUS.getName(),loginFellowEntity);
            return true;
        }else{
            throw new UnauthorizedException("密码错误，请联系管理员重置密码");
        }

    }

    public FellowEntity getLogin(HttpServletRequest request){
        FellowEntity loginFellowEntity = (FellowEntity) request.getSession().getAttribute("login_status");
        if (loginFellowEntity==null || loginFellowEntity.getId()<0){
            System.out.println("前端获取登录状态失败");
            return null;
        }else{
            FellowEntity fellow=this.baseMapper.selectById(loginFellowEntity.getId());
            if (fellow!=null) {
                System.out.println("用户"+loginFellowEntity.getName()+"前端获取登录状态成功");
                return fellow;
            }
            return null;
        }
    }

    @Override
    public allFellowVo transferAllFellowVo(FellowEntity fellowEntity) {
        allFellowVo allFellowVo = new allFellowVo();
        BeanUtils.copyProperties(fellowEntity,allFellowVo);
        return allFellowVo;
    }

    @Override
    public Boolean setRole(Integer id, Integer roleId) {
        FellowEntity fellow = this.baseMapper.selectById(id);
        if (fellow!=null){
            fellow.setRole(roleId);
            int i = this.baseMapper.updateById(fellow);
            return i>0;
        }else{
            throw new UnauthorizedException("用户不存在");
        }

    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        FellowEntity loginFellowEntity = (FellowEntity) request.getSession().getAttribute("login_status");
        if (loginFellowEntity==null || loginFellowEntity.getId()<0) {
            System.out.println("用户未登录");
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        request.getSession().removeAttribute("login_status");
        return true;

    }

    public Boolean resetPassword(Integer id,String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        FellowEntity fellow = this.baseMapper.selectById(id);
        if (fellow!=null){
            //使用md5加密
            String encryptedPwd = MyMD5Util.encrypt(password);
            System.out.println("重置密码加密后"+encryptedPwd);
            fellow.setPassword(encryptedPwd);
            int i = this.baseMapper.updateById(fellow);
            return i>0;
        }else{
            throw new UnauthorizedException("用户不存在");
        }
    }

    public List<allFellowVo> getUserFellow(){
        //获取所有普通用户的会员
        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_display",1).eq("role",3);
        List<FellowEntity> list = this.list(wrapper);
        List<allFellowVo> vos = new ArrayList<>();
        for (FellowEntity fellow : list) {
            vos.add(this.transferAllFellowVo(fellow));
        }
        return vos;

    }


}